package org.glutenberg;

import java.io.IOException;
import java.util.Vector;

import javax.microedition.lcdui.Canvas;


import org.glutenberg.util.StringUtils;

import com.sun.lwuit.Command;
import com.sun.lwuit.Display;
import com.sun.lwuit.Font;
import com.sun.lwuit.Form;
import com.sun.lwuit.Label;
import com.sun.lwuit.TextField;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.plaf.Style;

public class FindForm extends Form implements ActionListener {

	private Handbook hb;
	private TextField keywords;
	private Command exit;
	private Command find;
	private Command aboutCommand;

	public FindForm(Handbook hb) {
		this.hb = hb;
		this.setTitleComponent(this.getTitle("Cerca prodotti"));
		this.keywords = new FixedTextField();
		//this.keywords.setUseSoftkeys(false);
		TextField.setQwertyAutoDetect(true);
		//this.keywords.setReplaceMenu(false);
		this.keywords.setPreferredW(Display.getInstance().getDisplayWidth() - 10);
		this.addComponent(this.keywords);
		this.exit = new Command("Esci");
		this.find = new Command("Cerca");
		this.aboutCommand = About.getAboutCommand();
		this.addCommandListener(this);
		this.addCommand(this.find);
		this.addCommand(this.exit);
		this.addCommand(this.aboutCommand);
		this.setDefaultCommand(this.find);
	}
	
	private Label getTitle(String title){
		Label titleL = new Label(title);
		Style s = new Style();
		s.setFont(Font.createSystemFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_LARGE));
		titleL.setSelectedStyle(s);
		titleL.setUnSelectedStyle(s);
		return titleL;
	}

	public void actionPerformed(ActionEvent ev) {
		Command c = ev.getCommand();
		if(c==this.exit){
			this.hb.quit();
		} else if(c==this.find){
			try {
				String keyword = this.keywords.getText().trim().toLowerCase();
				Vector keywords = StringUtils.split(keyword," ");
				if(keywords.size()>0){
					this.hb.showResults(keywords);
				}
			} catch (IOException e) {
				this.hb.quit();
			}
		} else if(c==this.aboutCommand){
			this.hb.about(this);
		}
	}

}
